package com.wu.flandre.util;

import com.wu.flandre.component.GlobalConstant;
import com.wu.flandre.entity.wechat.WeChatAccessTokenEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * AccessToken获取工具类
 *
 * @author 50816
 * @date 2019年12月1日 18:47:29
 */
@Component
@Slf4j
public class AccessTokenUtil {

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.appsecret}")
    private String appsecret;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取AccessToken
     */
    @Scheduled(initialDelay = 1000, fixedRate = 7100 * 1000)
    private void getAccessToken() {
        ResponseEntity<WeChatAccessTokenEntity> getTokenResponse = null;
        String accessTokenUrl = GlobalConstant.GET_ACCESS_TOKEN_URL + "?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
        try {
            getTokenResponse = restTemplate.exchange(accessTokenUrl, HttpMethod.GET, null, WeChatAccessTokenEntity.class);
            if (getTokenResponse.getBody().getErrmsg() == null && getTokenResponse.getBody().getAccess_token() != null) {
                log.info("获取AccessToken成功:" + getTokenResponse.getBody().toString());
                DataCacheUtil.getDataCache().setAccessToken(getTokenResponse.getBody().getAccess_token());
            } else {
                log.error("获取AccessToken失败,错误码:" + getTokenResponse.getBody().getErrcode() + ",错误原因:" + getTokenResponse.getBody().getErrmsg());
            }
        } catch (Exception e) {
            log.error("获取AccessToken异常:" + e.getMessage());
        }
    }

}
